package com.example.idachuappone.promptly.dao.impl;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.idachuappone.promptly.dao.AddressDao;
import com.example.idachuappone.promptly.dao.DBHelper;
import com.example.idachuappone.promptly.entity.Address;
import com.lidroid.xutils.bitmap.BitmapGlobalConfig.BitmapCacheManagementTask;

public class AddressDaoImpl implements AddressDao {
	private Context context;
	DBHelper db;
	private SQLiteDatabase rd;
	private SQLiteDatabase wd;

	public AddressDaoImpl(Context context) {
		this.context = context;
		this.db = new DBHelper(context);
	}

	@Override
	public Address selectByName(String name) {
		this.rd = this.db.getReadableDatabase();
		Cursor cursor = this.rd.rawQuery("select * from addresshis where name=?", new String[] { new StringBuilder(
				String.valueOf(name)).toString() });
		Address addressHistory = null;
		if (cursor.moveToNext()) {
			addressHistory = new Address(cursor.getString(1),
					cursor.getString(BitmapCacheManagementTask.MESSAGE_FLUSH),
					cursor.getString(BitmapCacheManagementTask.MESSAGE_CLOSE));
		}
		cursor.close();
		this.rd.close();
		return addressHistory;
	}

	@Override
	public List<Address> selectAll() {
		this.rd = this.db.getReadableDatabase();
		Cursor cursor = this.rd.rawQuery("select * from addresshis", null);
		List<Address> list = new ArrayList();
		while (cursor.moveToNext()) {
			list.add(new Address(cursor.getString(1), cursor.getString(BitmapCacheManagementTask.MESSAGE_FLUSH), cursor
					.getString(BitmapCacheManagementTask.MESSAGE_CLOSE)));
		}
		cursor.close();
		this.rd.close();
		return list;
	}

	@Override
	public void add(Address addressHistory) {
		this.wd = this.db.getWritableDatabase();
		this.wd.execSQL("insert into addresshis(name,address) values(?,?)", new String[] { addressHistory.getName(),
				addressHistory.getCity() + addressHistory.getDistrict() + addressHistory.getName() });
		this.wd.close();
	}

	@Override
	public void deleteAll() {
		this.wd = this.db.getWritableDatabase();
		this.wd.execSQL("delete from addresshis");
		this.wd.close();
	}
}
